# -*- coding: utf-8 -*-
import sys, os
import re

import tkinter as tk
from datetime import datetime
from tkinter import filedialog

import xlsxwriter as xw

def check_for_page(line):
    # 找到 记账日期 货币 交易金额 联机余额 交易摘要 对手信息
    # 找到 Date Currency Transaction
    # 找到 Amount Balance Transaction Type Counter Party
    if line.find("记账日期 货币 交易金额") != -1:
        #print("Page : " + line)
        return True
    if line.find("Date") != -1 and line.find("Currency"):
        #print("Page : " + line)
        return True
    if line.find("Amount") != -1 and line.find("Balance"):
        #print("Page : " + line)
        return True
    if line.find("温馨提示") != -1 :
        #print("Page : " + line)
        return True
    #if line.find("————————") != -1 : # 这一行会导致一条交易数据丢失
    #    #print("Page : " + line)
    #    return True
    if line.find("验真") != -1 and line.find("在线服务"):
        #print("Page : " + line)
        return True
    return False


#datelist = ['2020年11月23日', '2020-11-23',
#            '二零二零年十一月二十三日', '二零年十一月二三日', '20年1月5日', '20年01月05日']
#
#for i in datelist:
#    print(isdate(i))
def isdate(datestr):
    from time import strptime
    #from time import strftime
    chinesenum = {'一': '1', '二': '2', '三': '3', '四': '4',
                  '五': '5', '六': '6', '七': '7', '八': '8', '九': '9', '零': '0', '十': '10'}
    strdate = ''
    for i in range(len(datestr)):
        temp = datestr[i]
        if temp in chinesenum:
            if temp == '十':
                if datestr[i+1] not in chinesenum:
                    strdate += chinesenum[temp]
                elif datestr[i-1] in chinesenum:
                    continue
                else:
                    strdate += '1'
            else:
                strdate += chinesenum[temp]
        else:
            strdate += temp

    pattern = ('%Y年%m月%d日', '%Y-%m-%d', '%y年%m月%d日', '%y-%m-%d')
    output = '%Y年%m月%d日'
    for i in pattern:
        try:
            ret = strptime(strdate, i)
            if ret:
                return True #strftime(output, ret)
        except:
            continue
    return False


# 流水里面有个很关键的特征
def find_money_item(line):
    flag_is_find_cn = False
    MONEY_COUNTRY = [ "CNY", "USD", "HKD", "AUD", "GPB", "EUR", "CAD", "JPY", "SGD", "NZD", "CHF"]
    for check_item in MONEY_COUNTRY:
        if line.find(check_item) != -1:
            flag_is_find_cn = True
            break#return True
    if flag_is_find_cn == False:
        return False

    try:
        line_array = line.split(" ", 1)
        # 如果这一行符合格式，那么就记录下来，先不返回
        if isdate(line_array[0]) == True:
            return True
    except Exception as e:
        #print(line)
        return False
    return False

# 如果某一行没有包含交易币种和时间，而它的上一行却有，那么怀疑它是上一行的数据，应该黏贴到上一行去
def check_for_item_line(line_cur, line_next):
    ret_str = ""
    # 登记当前行
    if find_money_item(line_cur):
        if find_money_item(line_next) == False:
            return line_cur + line_next
        return line_cur
    return ""

def trim_to_format(line, tok):
    # 找到以 数字 + '/' + 数字 结尾的部分，并删除（这个部分是属于页码那里的）
    # >>> a = '2024-03-31 CNY -127.00 0.00 快捷支付 微信转账3/6'
    # >>> re.sub(r'[0-9]/[0-9]$', '', a)
    #         '2024-03-31 CNY -127.00 0.00 快捷支付 微信转账'
    line = re.sub(r'[0-9]/[0-9]$', '', line)
    # 找到以 “—” 作为结尾的部分，并删除（这个部分是属于分隔符那里的）
    line = re.sub(r'-*$', '', line)
    line = re.sub(r'—*$', '', line)
    if tok != "":
       line = line.replace(" ", tok)
    return line

listOfLines  =  list()
listOfIgnore  =  list()


def do_parise(file_path):
    if file_path == "":
        return False
    output_list = list()
    all_line_index = 0
    # 打印第一页清单前的杂项信息
    #with  open  (file_path,  "r", encoding='utf-8')  as  myfile_debug:
    #    for  line in  myfile_debug:
    #        if check_for_page(line) == True:
    #            break
    #        print(line)

    # 初步过滤，把非表头的内容数据加载出来
    with  open  (file_path,  "r", encoding='utf-8')  as  myfile:
        line_str = ""
        for  line in  myfile:
            line_str = line.strip()
            all_line_index = all_line_index + 1
            if check_for_page(line_str) == True:
                listOfIgnore.append(line_str)
                #print("")
                #mark_as_page(i)
                #print("skip : " + line)
                continue

            ret = line
            listOfLines.append(ret)

    # 对数据进行进一步处理，处理掉额外的内容以及断行重新合并
    ok_cnt = 0
    for i in range(len(listOfLines)):
        cur_item = listOfLines[i]
        if i + 1 < len(listOfLines):
            nex_item = listOfLines[i + 1]
        else:
            nex_item = ""
        ret = check_for_item_line(cur_item.strip(), nex_item.strip())
        if ret == "":
            #listOfIgnore.append(cur_item.strip())
            #print("Skip " + cur_item)
            continue
        ok_cnt = ok_cnt + 1
        output_list.append(trim_to_format(ret, " | "))
    print("OK, "+ str(ok_cnt) + "/" + str(all_line_index))
    return output_list

    #print("Ignore :")
    #for item in listOfIgnore:
    #    print(item)

def xw_toExcel(output_list, fileName):  # xlsxwriter库储存数据到excel
    workbook = xw.Workbook(fileName)  # 创建工作簿
    worksheet1 = workbook.add_worksheet("sheet1")  # 创建子表
    worksheet1.activate()  # 激活表

    title = ['记账日期', '货币', '交易金额', '联机余额',  '交易摘要', '对手信息']  # 设置表头
    worksheet1.write_row('A1', title)  # 从A1单元格开始写入表头
    i = 2  # 从第二行开始写入数据
    for j in range(len(output_list)):
        line = output_list[j]
        insertData = line.split("|")
        #insertData = [output_list[j]["id"], output_list[j]["name"], output_list[j]["price"]]
        row = 'A' + str(i)
        worksheet1.write_row(row, insertData)
        i += 1
    workbook.close()  # 关闭表

def open_file(action, info_str):
    print(info_str)
    # 创建 tkinter 窗口
    root = tk.Tk()
    root.withdraw()  # 隐藏主窗口
    # 打开文件对话框，等待用户选择文件
    if action == "r":
        file_path = filedialog.askopenfilename(title=info_str, defaultextension='data.txt',filetypes=[("txt文件", ".txt"), ("所有文件", ".*")])
    else:
        file_path = filedialog.asksaveasfilename(title=info_str, defaultextension='output.xlsx',filetypes=[("Excel文件", ".xlsx")])
    # 检查用户是否选择了文件
    if file_path:
        print("文件路径是:", file_path)
    elif file_path == '':
        print("用户取消了文件选择")
    else:
        print("用户取消了文件选择")
    # 关闭 tkinter 窗口
    root.destroy()
    return file_path

file_name = open_file("r", '请选择要读取的txt文件：（文件内容是招商银行流水pdf文件的复制粘贴）')
output_list = do_parise(file_name)
if len(output_list) != 0:
    for item in output_list:
        print(item)
    file_name = open_file("w", '请选择要写到的Excel文件：')
    xw_toExcel(output_list, file_name)